<!-- 处置流程图 -->
<template>
    <div class="control list_container flex both-100 ">
        <Breadcrumb :title="pageTitle" />
        <div class="content_container">
            <!-- 新增 -->
            <el-form ref="searchForm" :inline="true" :model="searchMap" class="search_wrapper flex-space-between ">
                <div class="search ">
                    <el-row :gutter="20">
                        <el-col :span="3">
                            <el-form-item size="small">
                                <el-input v-model="searchMap.processDiagramName" placeholder="处置流程名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3">
                            <el-form-item size="small">
                                <el-input v-model="searchMap.prepressName" placeholder="预案名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item size="small">
                                <treeselect v-model="searchMap.deptName" :options="deptOptions" :normalizer="normalizer"
                                    placeholder="选择所属单位" />
                            </el-form-item>
                        </el-col>
                        <el-form-item size="small" class="flex">
                            <el-button @click="handleSearch()" class="btn_primary el-icon-search">查询</el-button>
                            <el-button @click="handleReset()" class="btn_cancel el-icon-refresh-left">重置</el-button>
                        </el-form-item>
                    </el-row>

                </div>
                <div class="edit">
                    <el-form-item class="flex">
                        <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
                    </el-form-item>
                </div>
            </el-form>
            <div class="table_container">
                <!-- 表格 -->
                <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%" height="500">
                    <el-table-column prop="alarmEventTypeId" label="告警类型" align="center">
                        <template slot-scope="scope">
                            <span>{{ getTypeName(scope.row.alarmEventTypeId) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="processDiagramName" label="处置流程名称" width="200" align="center"></el-table-column>
                    <el-table-column prop="deptName" label="所属单位" width="200" align="center"></el-table-column>
                    <el-table-column prop="prepressName" label="预案名称" width="200" align="center"></el-table-column>
                    <el-table-column label="操作" width="280">
                        <template slot-scope="scope">
                            <div>
                                <span type="text" class="tag_primary" size="small"
                                    @click="handleSelect(scope.row)">查看</span>
                                <span type="text" class="marginl-10 tag_primary" size="small"
                                    @click="handleEdit(scope.row)">编辑</span>
                                <span type="text" class="marginl-10 tag_warning" size="small"
                                    @click="handleDelete(scope.row)">删除</span>
                                <span>
                                    <span>
                                        <span class="el-dropdown-link" v-if="scope.row.diagramPic">
                                            <span @click="handleCommand(scope.row.diagramPic)" type="text"
                                                class="marginl-10 tag_warning" size="small">下载附件</span>
                                        </span>
                                        <span class="el-dropdown-link" v-else>
                                            <span type="text" class="marginl-10 tag_warning" size="small">暂无附件</span>
                                        </span>
                                    </span>
                                </span>


                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize"
                @change="getList"></Pagination>
        </div>

        <!-- 弹窗 详情 -->
        <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
            :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
            <div class="content">
                <el-form ref="form" :model="formModel" :rules="formRules" size="small" label-width="80px"
                    :disabled="title === '处置流程图详情'">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="告警类型" label-width="120px" prop="alarmEventTypeId">
                                <el-select filterable v-model="formModel.alarmEventTypeId" placeholder="请选择告警类型"
                                    style="width: 100%;">
                                    <el-option v-for="(item, index) in alarmEventTypeDataList" :label="item.eventName"
                                        :value="item.alarmEventTypeId"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="处置流程名称" label-width="120px" prop="processDiagramName">
                                <el-input v-model="formModel.processDiagramName" placeholder="请输入处置流程名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属单位:" prop="deptName" label-width="120px">
                                <treeselect v-model="formModel.deptName" :options="deptOptions"
                                    :disabled="title === '处置流程图详情'" :normalizer="normalizer" placeholder="选择上级部门" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预案名称" label-width="120px" prop="prepressName">
                                <el-input v-model="formModel.prepressName" placeholder="请输入备案号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="附件" label-width="120px">
                                <uploadFile :disabled="title === '处置流程图详情'" :value="formModel.diagramPic"
                                    :deleteFlag="deleteFlag" :fileType="fileType" @change="changeImg" @remove="removeImg"
                                    :key="uploadFileKey">
                                </uploadFile>
                                <p style="color:red;">支持扩展名：.pdf .bmp .gif .jpg .jpeg .png</p>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer" v-show="title === '处置流程图详情'">
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">关 闭</el-button>
            </div>
            <div slot="footer" class="dialog-footer" v-show="title !== '处置流程图详情'">
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
                <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="title" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
            <custom-title title="详细信息" />
            <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
                <!-- <template #alarmEventTypeId>
                    <dict-tag :options="dict.type.reserve_plan_type" :value="formModel.alarmEventTypeId" />
                </template> -->
                <template #diagramPic>
                    <uploadFile :isUploadShow="false" :value="formModel.diagramPic" :deleteFlag="deleteFlag"
                        :fileType="fileType" @change="changeImg" @remove="removeImg" :key="uploadFileKey">
                    </uploadFile>
                </template>
            </BaseDescriptions>
        </el-dialog>
    </div>
</template>
<script>
import { listDept } from '@/api'
import { processDiagram, processDiagramList, alarmEventTypeList } from '../api/index'

import uploadFile from '@/components/UploadFiles2/index'
import { handleTree } from '@/utils/ruoyi'

import axios from 'axios';

export default {
    name: 'emergency',
    dicts: ['reserve_plan_type'],
    components: {
        uploadFile
    },
    props: {
    },
    data() {
        return {
            uploadFileKey: 0,
            deleteFlag: false,
            dialogVisibleInfo: false,
            loading: true,
            pageTitle: '处置流程图',
            total: 0,
            title: '处置流程图详情',
            formType: 'basicInformation',
            dialogVisible: false,
            searchMap: {
                pageNum: 1,
                pageSize: 10,
            },
            descConfig: {
                size: 'medium',
                column: '2',
            },
            dataList: [],
            deptOptions: [],
            alarmEventTypeDataList: [],
            fileType: ['pdf', 'bmp', 'gif', 'jpg', 'jpeg', 'png'],
            // 提交表单数据
            formModel: {
                diagramPic: '',
            },
            reqType: 'post',
            formRules: {
                alarmEventTypeId: {
                    required: true,
                    message: "告警类型不能为空",
                    trigger: "change",
                },
                processDiagramName: {
                    required: true,
                    message: "处置流程名称不能为空",
                    trigger: "change",
                },
                deptId: {
                    required: true,
                    message: "所属单位不能为空",
                    trigger: "change",
                },
                prepressName: {
                    required: true,
                    message: "预案名称不能为空",
                    trigger: "change",
                },
            },
            descConfigItem: [
                {
                    fieIdName: 'alarmEventTypeName',
                    label: '告警类型',
                    span: 2,
                    // slotName: 'alarmEventTypeId',
                },
                {
                    fieIdName: 'processDiagramName',
                    label: '处置流程名称',
                    span: 2,
                },
                {
                    fieIdName: 'prepressName',
                    label: '预案名称',
                    span: 12,
                },
                {
                    fieIdName: 'diagramPic',
                    label: '附件',
                    span: 12,
                    slotName: 'diagramPic',
                },
            ],
        }
    },
    methods: {
        submitFrom() {
            console.log(this.formModel)
            console.log(this.deptOptions)
            this.findDeptIdByDeptName(this.deptOptions, this.formModel.deptName);
            this.$refs.form.validate((valid) => {
                if (valid) {
                    processDiagram(this.formModel, this.reqType).then(res => {
                        if (200 === res.code) {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                            });
                            this.dialogVisible = false
                            this.formModel = {}
                            this.getList()
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        //删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                processDiagram([row.processDiagramId], 'delete').then(res => {
                    if (200 === res.code) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList()
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //新增打开
        handleAdd() {
            this.uploadFileKey += 1
            this.title = "新增处置流程图"
            this.deleteFlag = false
            this.reqType = 'post'
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            this.formModel = {}
            this.formModel.diagramPic = ''
            this.$set(this.formModel, 'diagramPic', '')
            this.dialogVisible = true;
        },
        // 查询
        handleSearch() {
            this.getList()
        },
        // 重置
        handleReset() {
            this.searchMap = {
                pageNum: 1,
                pageSize: 10,
            }
            this.getList()
        },
        //编辑
        handleEdit(row) {
            this.uploadFileKey += 1
            this.title = "编辑处置流程图"
            this.formModel = row
            this.deleteFlag = false
            this.$set(this.formModel, 'diagramPic', row.diagramPic)
            this.reqType = 'put'
            this.dialogVisible = true;
        },
        //查看
        handleSelect(row) {
            this.uploadFileKey += 1
            this.deleteFlag = true
            this.title = "处置流程图详情"
            this.reqType = 'select'
            this.formModel = row
            this.dialogVisibleInfo = true;
            this.alarmEventTypeDataList.forEach(item => {
                if(item.alarmEventTypeId === row.alarmEventTypeId){
                    this.formModel.alarmEventTypeName = item.eventName;
                }
            })

        },
        findDeptIdByDeptName(treeData, targetName) {
            for (let item of treeData) {
                if (item.deptName === targetName) {
                    this.formModel.deptId = item.deptId;
                    break; // 如果找到了就停止搜索
                } else if (Array.isArray(item.children) && item.children.length > 0) {
                    this.findDeptIdByDeptName(item.children, targetName); // 递归查找子节点
                }
            }
        },
        getTypeName(id) {
            return this.alarmEventTypeDataList.find(item => item.alarmEventTypeId === id)?.eventName || '';
        },
        //下载
        handleDownload(row) {
            console.log(row)
            // this.downloadByBlob(this.$store.state.config.inFilePrefix + row.picUrl, 'pic')
        },
        handleCommand(command) {
            console.log(command)
            const extension = command.match(/\.(\w+)$/)[1];
            if (extension === 'pdf') {
                this.downloadPdfBlob(this.$store.state.config.inFilePrefix + command, '附件')
            } else {
                this.downloadByBlob(this.$store.state.config.inFilePrefix + command, '附件')
            }
        },
        downloadPdfBlob(url, name) {
            console.log('22')
            axios({
                url: url,
                method: 'GET',
                responseType: 'blob'
            }).then(res => {
                let blob = new Blob([res.data], { type: 'application/pdf' })
                let url = window.URL.createObjectURL(blob)
                let a = document.createElement('a')
                a.href = url
                a.download = name
                a.click()
                a.remove()
                window.URL.revokeObjectURL(url)
            })
        },
        downloadByBlob(url, name) {
            console.log('11')
            let image = new Image();
            image.setAttribute("crossOrigin", "anonymous");
            image.src = url;
            image.onload = () => {
                let canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                let ctx = canvas.getContext("2d");
                ctx.drawImage(image, 0, 0, image.width, image.height);
                canvas.toBlob(blob => {
                    let url = URL.createObjectURL(blob);
                    let a = document.createElement("a");
                    a.download = name;
                    a.href = url;
                    a.click();
                    a.remove();
                    // 用完释放URL对象
                    URL.revokeObjectURL(url);
                });
            };
        },
        handleStr(val) {
            console.log(val)
            const parts = val.split('/');
            return parts[parts.length - 1]
        },
        // 项目点图片修改
        changeImg(item) {
            console.log(item)
            if (!this.formModel.diagramPic) {
                this.formModel.diagramPic = ''
            }
            this.formModel.diagramPic = item.url
        },
        removeImg(item) {
            console.log(item)
            if (item.length <= 0) {
                this.formModel.diagramPic = ''
                console.log('0')
            }
            // this.formModel.diagramPic.splice(this.formModel.diagramPic.indexOf(item.url), 1)
        },
        /** 转换部门数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.deptName,
                label: node.deptName,
                children: node.children
            };
        },
        // 页面数据
        async getList() {
            const { code, rows, total } = await processDiagramList(this.searchMap)
            if (code === 200) {
                this.loading = false
                this.dataList = rows
                this.total = total
            }
        },
        // 告警数据
        async getalarmEventTypeList() {
            const { code, rows, } = await alarmEventTypeList({ pageNum: 1, pageSize: 100 })
            if (code === 200) {
                this.alarmEventTypeDataList = rows
            }
        },
        listDept() {
            listDept().then(response => {
                this.deptOptions = handleTree(response.data, "deptId");
            });
        },
    },
    mounted() {
        this.getList()
        this.listDept()
        this.getalarmEventTypeList()
    },
}
</script>
<style lang="less">
.control {
    .el-table__cell {
        .cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }

    .vue-treeselect__control {
        height: 32px !important;
    }
}
</style>
